<template>
	<view class="recharge-page">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left" @click="goBack">
				<text class="iconfont icon-arrow-left"></text>
			</view>
			<view class="navbar-title">充值</view>
			<view class="navbar-right" @click="goToDetail">
				<text>明细</text>
			</view>
		</view>
		
		<!-- 当前余额显示 -->
		<view class="balance-section">
			<view class="balance-icon">
				<image src="/static/images/credit-icon.png" class="credit-icon" mode="aspectFit"></image>
			</view>
			<view class="balance-amount">{{ currentCredits }}</view>
		</view>
		
		<!-- 充值套餐选择 -->
		<view class="packages-section">
			<view class="packages-grid">
				<view 
					v-for="item in packages" 
					:key="item.id"
					class="package-item"
					:class="{ 'selected': selectedPackage && selectedPackage.id === item.id }"
					@click="selectPackage(item)"
				>
					<!-- 折扣角标 -->
					<view v-if="item.discount_label" class="discount-label">
						{{ item.discount_label }}
					</view>
					
					<!-- 积分数量 -->
					<view class="package-credits">
						<image src="/static/images/credit-icon-small.png" class="credit-icon-small" mode="aspectFit"></image>
						<text class="credits-text">{{ item.total_credits }}</text>
					</view>
					
					<!-- 价格 -->
					<view class="package-price">
						<text class="price-symbol">¥</text>
						<text class="price-amount">{{ item.price }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 支付方式选择 -->
		<view class="payment-section">
			<view class="section-title">支付方式</view>
			<view class="payment-methods">
				<view 
					v-for="method in payMethods" 
					:key="method.id"
					class="payment-item"
					:class="{ 'selected': selectedPayMethod === method.id }"
					@click="selectPayMethod(method.id)"
				>
					<view class="payment-left">
						<image :src="method.icon" class="payment-icon" mode="aspectFit"></image>
						<text class="payment-name">{{ method.name }}</text>
					</view>
					<view class="payment-right">
						<view class="radio-btn" :class="{ 'checked': selectedPayMethod === method.id }">
							<text v-if="selectedPayMethod === method.id" class="iconfont icon-check"></text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部充值按钮 -->
		<view class="bottom-section">
			<view class="recharge-btn" 
				:class="{ 
					'disabled': !selectedPackage || paying,
					'paying': paying,
					'success': payStatus === 'success',
					'failed': payStatus === 'failed'
				}"
				@click="handleRecharge"
			>
				<!-- 支付中状态 -->
				<text v-if="paying">{{ payMessage || '支付中...' }}</text>
				<!-- 支付成功状态 -->
				<text v-else-if="payStatus === 'success'">✅ {{ payMessage }}</text>
				<!-- 支付失败状态 -->
				<text v-else-if="payStatus === 'failed'">❌ 重新支付</text>
				<!-- 正常状态 -->
				<text v-else-if="selectedPackage">¥{{ selectedPackage.price }}立即充值</text>
				<!-- 未选择套餐 -->
				<text v-else>请选择充值套餐</text>
			</view>
			
			<view class="agreement">
				<text>充值即同意 </text>
				<text class="agreement-link" @click="showAgreement">《充值协议》</text>
			</view>
			
			<view class="customer-service">
				<text>如遇问题，请点击问题反馈</text>
				<text>或联系客服：18059273485</text>
			</view>
		</view>
		
		<!-- 加载遮罩 -->
		<view v-if="loading" class="loading-mask">
			<view class="loading-spinner">
				<text>加载中...</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { getCreditPackages, createRechargeOrder, getPayParams, getOrderStatus } from '@/api/ai-trip/credit.js'
	import { getUserInfo } from '@/api/ai-trip/auth.js'
	
	export default {
		data() {
			return {
				loading: false,
				currentCredits: 0,           // 当前积分
				packages: [],                // 套餐列表
				selectedPackage: null,       // 选中的套餐
				selectedPayMethod: 'wechat', // 选中的支付方式
				payMethods: [
					{ 
						id: 'wechat', 
						name: '微信支付', 
						icon: 'https://cdn.zhzfpn.cn/wechat.png' 
					}
				],
				// 支付相关状态
				paying: false,               // 支付进行中
				currentOrderNo: '',          // 当前订单号
				payTimer: null,              // 轮询定时器
				payRetryCount: 0,            // 轮询重试次数
				maxRetryCount: 40,           // 最大重试次数 (40次 * 3秒 = 2分钟)
				payStatus: '',               // 支付状态：'' | 'paying' | 'success' | 'failed'
				payMessage: ''               // 支付状态消息
			}
		},
		
		onLoad() {
			this.initPage()
		},
		
		onShow() {
			// 页面显示时刷新用户积分
			this.getCurrentCredits()
		},
		
		onUnload() {
			// 页面卸载时清理定时器
			this.clearPaymentPolling()
		},
		
		methods: {
			// 初始化页面
			async initPage() {
				try {
					this.loading = true
					await Promise.all([
						this.getCreditPackagesList(),
						this.getCurrentCredits()
					])
				} catch (error) {
					console.error('页面初始化失败:', error)
					uni.showToast({
						title: '页面加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},
			
			// 获取充值套餐列表
			async getCreditPackagesList() {
				try {
					const res = await getCreditPackages()
					if (res.code === 200) {
						this.packages = res.data || []
						console.log('获取套餐列表成功:', this.packages)
					} else {
						throw new Error(res.message || '获取套餐列表失败')
					}
				} catch (error) {
					console.error('获取套餐列表失败:', error)
					uni.showToast({
						title: error.message || '获取套餐列表失败',
						icon: 'none'
					})
				}
			},
			
			// 获取用户当前积分
			async getCurrentCredits() {
				try {
					const res = await getUserInfo()
					if (res.code === 200) {
						this.currentCredits = res.data.credits || 0
					}
				} catch (error) {
					console.error('获取用户积分失败:', error)
				}
			},
			
			// 选择套餐
			selectPackage(packageItem) {
				this.selectedPackage = packageItem
				console.log('选中套餐:', packageItem)
			},
			
			// 选择支付方式
			selectPayMethod(methodId) {
				this.selectedPayMethod = methodId
				console.log('选中支付方式:', methodId)
			},
			
			// 处理充值
			async handleRecharge() {
				if (!this.selectedPackage) {
					uni.showToast({
						title: '请选择充值套餐',
						icon: 'none'
					})
					return
				}
				
				// 防止重复提交
				if (this.paying) {
					return
				}
				
				try {
					this.paying = true
					this.payStatus = 'paying'
					this.payMessage = '正在创建订单...'
					
					// 步骤1: 创建充值订单
					const orderRes = await createRechargeOrder({
						package_id: this.selectedPackage.id
					})
					
					if (orderRes.code !== 200) {
						throw new Error(orderRes.message || '订单创建失败')
					}
					
					console.log('订单创建成功:', orderRes.data)
					this.currentOrderNo = orderRes.data.order_no
					this.payMessage = '正在获取支付参数...'
					
					// 步骤2: 获取支付参数
					const payRes = await getPayParams({
						order_no: orderRes.data.order_no
					})
					
					if (payRes.code !== 200) {
						throw new Error(payRes.message || '获取支付参数失败')
					}
					
					console.log('获取支付参数成功:', payRes.data)
					this.payMessage = '正在调起微信支付...'
					
					// 步骤3: 调起微信支付
					await this.callWechatPay(payRes.data)
					
				} catch (error) {
					console.error('充值失败:', error)
					this.handlePaymentFail(error.message || '充值失败，请稍后重试')
				}
			},
			
			// 调起微信支付
			async callWechatPay(payParams) {
				return new Promise((resolve, reject) => {
					console.log('调起微信支付:', payParams)
					
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: payParams.timeStamp,
						nonceStr: payParams.nonceStr,
						package: payParams.package,
						signType: payParams.signType,
						paySign: payParams.paySign,
						success: (res) => {
							console.log('微信支付成功回调:', res)
							this.payMessage = '支付成功，正在确认...'
							// 开始轮询支付状态
							this.startPaymentPolling()
							resolve(res)
						},
						fail: (err) => {
							console.error('微信支付失败:', err)
							// 处理用户取消支付
							if (err.errMsg && err.errMsg.includes('cancel')) {
								this.handlePaymentFail('用户取消支付')
							} else {
								this.handlePaymentFail(err.errMsg || '支付失败')
							}
							reject(err)
						}
					})
				})
			},
			
			// 开始支付状态轮询
			startPaymentPolling() {
				this.payRetryCount = 0
				this.checkPaymentStatus()
			},
			
			// 检查支付状态
			async checkPaymentStatus() {
				try {
					const res = await getOrderStatus(this.currentOrderNo)
					
					if (res.code === 200) {
						const orderData = res.data
						
						// 支付成功
						if (orderData.pay_status === 20) {
							this.handlePaymentSuccess(orderData)
							return
						}
						
						// 支付失败
						if (orderData.pay_status === 30) {
							this.handlePaymentFail('支付失败')
							return
						}
					}
					
					// 继续轮询
					this.payRetryCount++
					if (this.payRetryCount >= this.maxRetryCount) {
						this.handlePaymentFail('支付超时，请稍后查看订单状态')
						return
					}
					
					// 3秒后继续查询
					this.payTimer = setTimeout(() => {
						this.checkPaymentStatus()
					}, 3000)
					
				} catch (error) {
					console.error('查询支付状态失败:', error)
					this.payRetryCount++
					
					if (this.payRetryCount >= this.maxRetryCount) {
						this.handlePaymentFail('网络异常，请稍后查看订单状态')
						return
					}
					
					// 3秒后继续查询
					this.payTimer = setTimeout(() => {
						this.checkPaymentStatus()
					}, 3000)
				}
			},
			
			// 处理支付成功
			handlePaymentSuccess(orderData) {
				console.log('支付成功:', orderData)
				
				// 清理定时器
				this.clearPaymentPolling()
				
				// 更新状态
				this.payStatus = 'success'
				this.payMessage = `充值成功！获得 ${orderData.total_credits} 积分`
				this.paying = false
				
				// 显示成功提示
				uni.showToast({
					title: '充值成功！',
					icon: 'success',
					duration: 2000
				})
				
				// 刷新用户积分
				this.getCurrentCredits()
				
				// 2秒后重置状态
				setTimeout(() => {
					this.payStatus = ''
					this.payMessage = ''
					this.currentOrderNo = ''
				}, 2000)
			},
			
			// 处理支付失败
			handlePaymentFail(message) {
				console.log('支付失败:', message)
				
				// 清理定时器
				this.clearPaymentPolling()
				
				// 更新状态
				this.payStatus = 'failed'
				this.payMessage = message
				this.paying = false
				
				// 显示失败提示
				uni.showToast({
					title: message,
					icon: 'none',
					duration: 3000
				})
				
				// 3秒后重置状态
				setTimeout(() => {
					this.payStatus = ''
					this.payMessage = ''
					this.currentOrderNo = ''
				}, 3000)
			},
			
			// 清理支付轮询
			clearPaymentPolling() {
				if (this.payTimer) {
					clearTimeout(this.payTimer)
					this.payTimer = null
				}
				this.payRetryCount = 0
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},
			
			// 前往明细页面
			goToDetail() {
				// TODO: 跳转到积分明细页面
				uni.showToast({
					title: '功能开发中...',
					icon: 'none'
				})
			},
			
			// 显示充值协议
			showAgreement() {
				// TODO: 显示充值协议弹窗
				uni.showToast({
					title: '充值协议',
					icon: 'none'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.recharge-page {
		min-height: 100vh;
		background: linear-gradient(180deg, #1a1a1a 0%, #2d2d2d 100%);
		color: #ffffff;
	}
	
	/* 自定义导航栏 */
	.custom-navbar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 88rpx;
		padding: 0 30rpx;
		background: #1a1a1a;
		
		.navbar-left, .navbar-right {
			width: 120rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			
			.iconfont {
				font-size: 36rpx;
				color: #7ED321;
			}
		}
		
		.navbar-right {
			justify-content: flex-end;
			color: #999999;
			font-size: 28rpx;
		}
		
		.navbar-title {
			font-size: 32rpx;
			font-weight: 500;
			color: #ffffff;
		}
	}
	
	/* 余额显示区域 */
	.balance-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 80rpx 0;
		
		.balance-icon {
			margin-bottom: 20rpx;
			
			.credit-icon {
				width: 120rpx;
				height: 120rpx;
			}
		}
		
		.balance-amount {
			font-size: 120rpx;
			font-weight: bold;
			color: #7ED321;
		}
	}
	
	/* 套餐选择区域 */
	.packages-section {
		padding: 0 30rpx;
		margin-bottom: 60rpx;
		
		.packages-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;
			
			.package-item {
				position: relative;
				background: #333333;
				border: 2rpx solid transparent;
				border-radius: 16rpx;
				padding: 30rpx 20rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				transition: all 0.3s ease;
				
				&.selected {
					border-color: #7ED321;
					background: rgba(126, 211, 33, 0.1);
				}
				
				.discount-label {
					position: absolute;
					top: -2rpx;
					right: -2rpx;
					background: #FF6B6B;
					color: #ffffff;
					font-size: 20rpx;
					padding: 6rpx 12rpx;
					border-radius: 0 14rpx 0 14rpx;
					transform: scale(0.8);
				}
				
				.package-credits {
					display: flex;
					align-items: center;
					margin-bottom: 15rpx;
					
					.credit-icon-small {
						width: 40rpx;
						height: 40rpx;
						margin-right: 8rpx;
					}
					
					.credits-text {
						font-size: 32rpx;
						font-weight: bold;
						color: #7ED321;
					}
				}
				
				.package-price {
					display: flex;
					align-items: baseline;
					
					.price-symbol {
						font-size: 24rpx;
						color: #ffffff;
					}
					
					.price-amount {
						font-size: 36rpx;
						font-weight: bold;
						color: #ffffff;
					}
				}
			}
		}
	}
	
	/* 支付方式区域 */
	.payment-section {
		padding: 0 30rpx;
		margin-bottom: 120rpx;
		
		.section-title {
			font-size: 28rpx;
			color: #999999;
			margin-bottom: 30rpx;
		}
		
		.payment-methods {
			.payment-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx 0;
				border-bottom: 1rpx solid #444444;
				
				&:last-child {
					border-bottom: none;
				}
				
				.payment-left {
					display: flex;
					align-items: center;
					
					.payment-icon {
						width: 60rpx;
						height: 60rpx;
						margin-right: 20rpx;
					}
					
					.payment-name {
						font-size: 32rpx;
						color: #ffffff;
					}
				}
				
				.payment-right {
					.radio-btn {
						width: 40rpx;
						height: 40rpx;
						border: 2rpx solid #666666;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						
						&.checked {
							border-color: #7ED321;
							background: #7ED321;
							
							.iconfont {
								font-size: 24rpx;
								color: #ffffff;
							}
						}
					}
				}
			}
		}
	}
	
	/* 底部区域 */
	.bottom-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #1a1a1a;
		padding: 30rpx;
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
		
		.recharge-btn {
			width: 100%;
			height: 88rpx;
			background: #7ED321;
			border-radius: 44rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			font-weight: bold;
			color: #000000;
			margin-bottom: 20rpx;
			transition: all 0.3s ease;
			
			&.disabled {
				background: #666666;
				color: #999999;
			}
			
			&.paying {
				background: #FF9500;
				color: #ffffff;
				
				/* 添加加载动画效果 */
				&::after {
					content: '';
					width: 20rpx;
					height: 20rpx;
					border: 2rpx solid rgba(255, 255, 255, 0.3);
					border-top: 2rpx solid #ffffff;
					border-radius: 50%;
					margin-left: 10rpx;
					animation: loading-spin 1s linear infinite;
				}
			}
			
			&.success {
				background: #4CAF50;
				color: #ffffff;
			}
			
			&.failed {
				background: #F44336;
				color: #ffffff;
			}
		}
		
		.agreement {
			text-align: center;
			font-size: 24rpx;
			color: #999999;
			margin-bottom: 20rpx;
			
			.agreement-link {
				color: #7ED321;
				text-decoration: underline;
			}
		}
		
		.customer-service {
			text-align: center;
			font-size: 22rpx;
			color: #666666;
			line-height: 1.5;
		}
	}
	
	/* 加载遮罩 */
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
		
		.loading-spinner {
			background: #333333;
			color: #ffffff;
			padding: 30rpx 60rpx;
			border-radius: 16rpx;
			font-size: 28rpx;
		}
	}
	
	/* 加载动画 */
	@keyframes loading-spin {
		0% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(360deg);
		}
	}
</style>
